In most of the applications, you need to have some static JSON data with which you can create and test the application without directly using the production data.
If you’re building an e-commerce application, you may need a list of product details with the product name, image, and price to test.
If you want to showcase something then first you will need some data to display on the UI.
So in this tutorial, you will see how to easily generate any amount of required data using a very popular npm library faker.
Update: Faker npm package is no longer available. Instead you can use faker-js which is similar to faker.
Prerequisites
You will need the following to complete this tutorial:
- Node.js installed locally
This tutorial was verified with Node v13.14.0, npm v6.14.4, faker v4.1.0, express v4.17.1, lodash v4.17.19 and nodemon v2.0.4
Installation
To install the library and other dependencies execute the following command from the terminal:
npm install faker@4.1.0 express@4.17.1 lodash@4.17.19 nodemon@2.0.4
Import the library in the following way
const faker = require('faker');
Using APIs
Following are some of the API categories provided by the library
- address
- commerce
- company
- database
- finance
- hacker
- helpers
- image
Each category provides various functions to access the data.
Get random country, city, state and zip code:
const country = faker.address.country(); // Singapore
const city = faker.address.city(); // Laverneberg
const state = faker.address.state(); // West Virginia
const zipCode = faker.address.zipCode(); // 57449-4128
Get random product name, price and color:
const product = faker.commerce.product(); // Table
const price = faker.commerce.price(); // 458.00
const color = faker.commerce.color(); // Cyan
Let’s build a simple application in Node.js where you provide a count of records you want and the application will generate that much data in the JSON format.
Initial Setup
Create a new folder mock-json-data-generator and initialize the package.json file
mkdir mock-json-data-generator
cd mock-json-data-generator
npm init -y
Now, install the faker , lodash, express and nodemon npm libraries
fakerwill be used to generate random mock datalodashwill be used to execute a function for a certain number of timesexpresswill be used to create REST APIsnodemonwill be used to restart the Express server if any file content is changed
Execute the following command from the mock-json-data-generator folder:
npm install faker@4.1.0 lodash@4.17.19 express@4.17.1 nodemon@2.0.4
Add a new start script inside package.json file
"scripts": {
"start": "nodemon index.js"
}
Your package.json file will look like this now

Get a List of Random Addresses
Create a new index.js file and add the following code inside it:
const express = require('express');
const faker = require('faker');
const _ = require('lodash');
const app = express();
app.get('/address', (req, res) => {
const count = req.query.count;
if (!count) {
return res
.status(400)
.send({ errorMsg: 'count query parameter is missing.' });
}
res.send(
_.times(count, () => {
const address = faker.address;
return {
country: address.country(),
city: address.city(),
state: address.state(),
zipCode: address.zipCode(),
latitude: address.latitude(),
longitude: address.longitude()
};
})
);
});
app.listen(3030, () => {
console.log('server started on port 3030');
});
In the above file,
- First, we imported all the required packages
- Then created an express app by calling the
expressfunction
const app = express();
- Then created a
/addressroute - Then we’re checking if the user has provided the
countquery parameter which specifies the number of records to get back
const count = req.query.count;
if (!count) {
return res
.status(400)
.send({ errorMsg: 'count query parameter is missing.' });
}
- If the
countdoes not exist then we are displaying an error message - Then we’re using the
timesmethod provided bylodashwhich will execute the provided functioncountnumber of times. Lodash library is optimized for performance so instead of using an arraymapmethod to generate for example 1000 records, we’re usinglodashlibrary so the response will be quicker.
_.times(count, () => {
const address = faker.address;
return {
country: address.country(),
city: address.city(),
state: address.state(),
zipCode: address.zipCode(),
latitude: address.latitude(),
longitude: address.longitude()
};
})
- The
timesmethod returns an array. In the provided arrow function, we’re returning an object with the randomly generated values so the output oftimesmethod will be an array of objects with the generated values. - Then we’re sending that result using
sendmethod of response object usingres.send - Then at the end, we’re starting the
Express.jsserver on port3030
app.listen(3030, () => {
console.log('server started on port 3030');
});
Now, start the application by executing the following command from the terminal:
npm run start
and access the application by visiting http://localhost:3030/address?count=10
Tip: To get the formatted JSON as shown above, you can install the JSON Formatter Google Chrome extension.
If you don’t provide the count query parameter, then you will get an error as can be seen below.

Get a List of Random Products
Add another /products route to get the list of products.
app.get('/products', (req, res) => {
const count = req.query.count;
if (!count) {
return res.status(400).send({
errorMsg: 'count query parameter is missing.'
});
}
res.send(
_.times(count, () => {
const commerce = faker.commerce;
return {
product: commerce.product(),
price: commerce.price(),
color: commerce.color()
};
})
);
});
In this code, instead of faker.address, we’ve used faker.commerce and its related methods.

Get a List of Random Images
Add another /images route to get the list of images.
app.get('/images', (req, res) => {
const count = req.query.count;
if (!count) {
return res.status(400).send({
errorMsg: 'count query parameter is missing.'
});
}
res.send(
_.times(count, () => {
const image = faker.image;
return {
image: image.image(),
avatar: image.avatar()
};
})
);
});

Get a List of Random Words
Add another /random route to get the list of random words.
app.get('/random', (req, res) => {
const count = req.query.count;
if (!count) {
return res.status(400).send({
errorMsg: 'count query parameter is missing.'
});
}
res.send(
_.times(count, () => {
const random = faker.random;
return {
word: random.word(),
words: random.words()
};
})
);
});
In this code, we’ve used faker.random and its related methods.

Get a List of Random Users
Add another /users route to get the list of random users.
app.get('/users', (req, res) => {
const count = req.query.count;
if (!count) {
return res.status(400).send({
errorMsg: 'count query parameter is missing.'
});
}
res.send(
_.times(count, () => {
const user = faker.name;
return {
firstName: user.firstName(),
lastName: user.lastName(),
jobTitle: user.jobTitle()
};
})
);
});
In this code, we’ve used faker.name and its related methods.

Get a List of Random Lorem Ipsum Text
Add another /lorem route to get the list of random lorem ipsum paragraphs.
app.get('/lorem', (req, res) => {
const count = req.query.count;
if (!count) {
return res.status(400).send({
errorMsg: 'count query parameter is missing.'
});
}
res.send(
_.times(count, () => {
const lorem = faker.lorem;
return {
paragraph: lorem.paragraph(),
sentence: lorem.sentence(),
paragraphs: lorem.paragraphs()
};
})
);
});
In this code, we’ve used faker.lorem and its related methods.

Get a List of Random User Information
Faker library also provides a set of helpers like createCard, userCard, createTransaction.
Add another /userCard route to get the list of the random card of user information like name, email, address, website, company.
app.get('/userCard', (req, res) => {
const count = req.query.count;
if (!count) {
return res.status(400).send({
errorMsg: 'count query parameter is missing.'
});
}
res.send(
_.times(count, () => {
const helpers = faker.helpers;
return {
userCard: helpers.userCard()
};
})
);
});
In this code, we’ve used faker.helpers and its userCard method.

In addition to the above user details, If we want the user's posts and transaction details, we can use the createCard helper method
Add another /createCard route to get the data of users posts and transactions in addition to the other details
app.get('/createCard', (req, res) => {
const count = req.query.count;
if (!count) {
return res.status(400).send({
errorMsg: 'count query parameter is missing.'
});
}
res.send(
_.times(count, () => {
const helpers = faker.helpers;
return {
createCard: helpers.createCard()
};
})
);
});
In this code, we’ve used faker.helpers and its createCard method.

Faker provides a lot of other details which you can check at this url.
Conclusion
As you have seen, the Faker library provides a lot of API functions to easily generate random data. It’s also very useful when you want to build something quickly without wasting hours of time for creating the data to work with.
You can find the complete source code for this application here.
Thanks for reading!
Check out my recently published Mastering Redux course.
In this course, you will build 3 apps along with food ordering app and you'll learn:
- Basic and advanced Redux
- How to manage the complex state of array and objects
- How to use multiple reducers to manage complex redux state
- How to debug Redux application
- How to use Redux in React using react-redux library to make your app reactive.
- How to use redux-thunk library to handle async API calls and much more
and then finally we'll build a complete food ordering app from scratch with stripe integration for accepting payments and deploy it to the production.
Want to stay up to date with regular content regarding JavaScript, React, Node.js? Follow me on LinkedIn.


Comments (0)